package com.zh.juc.cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @Author: zhanghuan
 * @date: 2022/10/18 20:51
 * @description: create it
 * 自旋锁
 * 通过CAS操作完成自旋锁，A线程先调用myLock方法自己持有锁5秒，B线程随后进来发现当前线程持有锁，所以只能通过自旋等待，知道A释放锁后B抢到
 *
 */
public class SpinLockDemo {
    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    public void lock() {
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName() + "\t" + "come in.........");
        while (!atomicReference.compareAndSet(null, thread)) {
            //
        }
    }

    public void unLock() {
        Thread thread = Thread.currentThread();
        atomicReference.compareAndSet(thread, null);
        System.out.println(Thread.currentThread().getName() + "\t" + "unlock over.........");
    }

    public static void main(String[] args) {
        SpinLockDemo spinLockDemo = new SpinLockDemo();
        new Thread(() -> {
            try {
                spinLockDemo.lock();
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            spinLockDemo.unLock();

        }, "A").start();
        // 暂停1秒 保证A线程先启动
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            spinLockDemo.lock();
            spinLockDemo.unLock();
        }, "B").start();



    }
}
